import { useState, useEffect } from 'react';

interface SpeechRecognitionOptions {
  onResult: (result: string) => void;
  onError?: (error: string) => void;
}

const useSpeechRecognition = ({ onResult, onError }: SpeechRecognitionOptions) => {
  const [isListening, setIsListening] = useState(false);
  const [hasRecognitionSupport, setHasRecognitionSupport] = useState(false);
  const [recognition, setRecognition] = useState<any>(null);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
      if (SpeechRecognition) {
        setHasRecognitionSupport(true);
        const recognitionInstance = new SpeechRecognition();
        recognitionInstance.continuous = false;
        recognitionInstance.lang = 'zh-CN';
        recognitionInstance.interimResults = false;
        
        recognitionInstance.onresult = (event: any) => {
          const transcript = event.results[0][0].transcript;
          onResult(transcript);
        };
        
        recognitionInstance.onerror = (event: any) => {
          setIsListening(false);
          onError?.(event.error);
        };
        
        setRecognition(recognitionInstance);
      }
    }
  }, [onResult, onError]);

  const startListening = () => {
    if (recognition) {
      recognition.start();
      setIsListening(true);
    }
  };

  const stopListening = () => {
    if (recognition) {
      recognition.stop();
      setIsListening(false);
    }
  };

  return {
    isListening,
    startListening,
    stopListening,
    hasRecognitionSupport
  };
};

export default useSpeechRecognition;